import React, { Component } from 'react'
import { deepFullCopy, messages, queryCurrencyPrecision } from "share/common";
import moment from "moment";
import { Icon, Menu, message, notification, Popover, Radio } from "antd";
import Partner from "containers/pay/template/partner"
import openSlideFrame from "share/openSlideFrame";
import confirmPaymentService from "../confirm-payment.service";
import selectorData from "share/selectorData";
import Department from "components/template/department";

/**
 * prending_pay 待确认
 * pay_in_process 待付款
 * pay_finished 已付款
 * pay_cancel 支付取消
 * 后台接口tab对应的key
 */

const DataHoc = WrappedComponent => {

  class Hoc extends Component {

    setWrappedInstance = ref => {
      this.wrappedInstance = ref;
    };

    columns = [
      { title: messages('common.applicant')/*申请人*/, dataIndex: 'applicantName' },
      { title: messages('common.user.id')/*工号*/, dataIndex: 'applicantEmployeeId' },
      {
        title: messages('common.submit.date')/*提交日期*/, dataIndex: 'lastSubmittedDate', width: 120,
        render: value => moment(value).format('YYYY-MM-DD'), sorter: true
      },
      {
        title: messages('finance-4.key60')/*单据类型*/, dataIndex: 'formName',
        render: value => <Popover content={value}>{value}</Popover>, sorter: true
      },
      {
        title: messages('common.document.code')/*单号*/, dataIndex: 'businessCode',
        render: (value, record) => {
          let showText = record.parentBusinessCode ? `${record.parentBusinessCode}-${value}` : value;
          return (
            <Popover content={showText}>
              {showText}
            </Popover>
          )
        }, sorter: true
      },
      {
        title: messages('finance-4.key321')/*收款方类型*/, dataIndex: 'payeeType',
        render: value => value === 1001 ? messages('finance-4.key304')/*供应商*/ : messages('finance-4.key303')/*员工*/
      },
      { title: messages('finance-4.key302')/*收款方*/, dataIndex: 'payeeName' },
      {
        title: messages('finance-4.key62')/*收款账号*/, dataIndex: 'accountNumber',
        render: value => <Popover content={value}>{value}</Popover>
      },
      {
        title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 60
      },
      {
        title: messages('finance-4.key322')/*待支付金额*/, dataIndex: 'realPaymentAmount', sorter: true,
        render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
      },
      {
        title: messages('finance-4.key323')/*凭证编号*/, hide: true, dataIndex: 'origDocumentSequence',
        render: value => <Popover content={value ? value : '-'}>
          {value ? value : '-'}
        </Popover>
      }
    ];

    getColumns = key => {
      let copyColumns = deepFullCopy(this.columns);
      switch (key) {
        case 'prending_pay':
          copyColumns.push({
            title: messages('finance-4.key272')/*单据公司*/, dataIndex: 'docCompanyName', sorter: true
          });
          break;
        case 'pay_in_process':
          break;
        case 'pay_finished':
          copyColumns[9].title = messages('finance-4.key324')/*已支付金额*/;
          break;
        case 'pay_cancel':
          copyColumns[9].title = messages('finance-4.key325')/*取消支付金额*/;
          copyColumns.push({ title: messages('finance-4.key326')/*取消理由*/, dataIndex: 'reason' });
          copyColumns.map((item) => {
            item.dataIndex === 'lastSubmittedDate' && (item.dataIndex = 'submittedDate');
            item.dataIndex === 'businessCode' && (item.dataIndex = 'childBusinessCode');
            item.dataIndex === 'applicantEmployeeId' && (item.dataIndex = 'employeeID');
            item.sorter = false;
          });
          break;
      }
      return copyColumns;
    };

    handlePartner = () => {
      let copyPartner = Partner;
      copyPartner.parser = value => value && value.partnerCategory ? {
        payeeType: value.partnerCategory.value === "EMPLOYEE" ? '1002' : '1001',
        payeeId: value.partnerId[0] ? value.partnerId[0].id : null
      } : null;
      return copyPartner;
    };

    searchForm = [
      {
        id: 'formOids', label: messages('finance-4.key273')/*表单类型*/, component: 'AllSelector',
        props: {
          type: 'authority_form',
          labelKey: 'formName',
          params: { formType: 1002 }
        },
        parser: value => ({ formOids: value ? value.map(item => item.formOID) : undefined })
      },
      {
        id: 'dateRange', label: messages('common.submit.date')/*提交日期*/, component: 'DateRangePicker',
        parser: value => ({
          submittedDateStart: value && value[0] ? moment(moment(value[0]).format('YYYY-MM-DD 00:00:00')).utc().format() : undefined,
          submittedDateEnd: value && value[1] ? moment(moment(value[1]).format('YYYY-MM-DD 23:59:59')).utc().format() : undefined
        }),
        initialValue: [moment().subtract(3, 'month'), moment()],
      },
      {
        id: 'approveDateRange', label: messages('finance-4.key278')/*审核日期*/, component: 'DateRangePicker',
        parser: value => ({
          auditDateStart: value && value[0] ? moment(moment(value[0]).format('YYYY-MM-DD 00:00:00')).utc().format() : undefined,
          auditDateEnd: value && value[1] ? moment(moment(value[1]).format('YYYY-MM-DD 23:59:59')).utc().format() : undefined
        })
      },
      {
        id: 'businessCode', label: messages('common.document.code')/*单号*/, component: 'Selector',
        props: {
          placeholder: messages('common.please.input')/*请输入*/ + messages('common.document.code')/*单号*/,
          selectorItem: Object.assign(selectorData['business_code_expense'], { dynamicUrl: true }),
          params: {
            status: 'prending_pay'
          }
        }
      },
      {
        id: 'applicantOid', label: messages('common.applicant')/*申请人*/, component: 'Selector',
        props: {
          selectorItem: Object.assign(selectorData['user'], { label: option => (`${option.employeeID}-${option.fullName}${(option.status !== 1001 ? (
              `（${option.status === 1002 ? messages('finance-4.key74')/*待离职员工*/ : messages('finance-4.key75')/*离职员工*/}）`
            ) : '')}`)
          }),
          placeholder: messages('common.please.input')/*请输入*/ + messages('finance-4.key327')/*姓名／工号*/,
          params: {
            status: 'all',
            roleType: 'TENANT'
          }
        }
      },
      {
        id: 'auditorOid', label: messages('finance-4.key279')/*审核人*/, component: 'Chooser',
        props: {
          type: 'finance-auditable-users',
          labelKey: 'fullName',
          valueKey: 'userOID',
          single: true
        },
        parser: value => ({ auditorOid: value ? value.map(item => item.userOID)[0] : undefined })
      },
      {
        id: 'corporationOids', label: messages('finance-4.key328')/*法人实体*/, component: 'Chooser',
        props: {
          type: 'corporation_entity',
          labelKey: "companyName",
          valueKey: "companyReceiptedOID"
        },
        parser: value => ({ corporationOids: value ? value.map(item => item.companyReceiptedOID) : undefined })
      }, this.handlePartner(),
      {
        id: 'departmentOids', label: messages('common.department')/*部门*/, component: <Department/>,
        parser: value => ({ departmentOids: value ? value.map(item => item.departmentOID) : undefined }),
        tagParser: value => (value.map(item => item.title).join(','))
      },
      {
        id: 'companyIds', label: messages('finance-4.key20')/*公司*/, component: 'Chooser',
        props: {
          type: 'permission_company',
          labelKey: 'name',
          valueKey: 'id',
          single: true,
          listExtraParams: { enabled: true }
        },
        parser: value => ({ companyIds: value ? value.map(item => item.id) : undefined }),
        tagParser: value => (value.map(item => item.name).join(','))
      }
    ];

    onRadioChange = (isInUsual, value) => {
      if (!isInUsual) {
        this.wrappedInstance.handleChangeStatus(value);
      }
    };

    handleChangeStatus = () => {
      const search = this.wrappedInstance.advancedTableRef.advancedSearchRef;
      search.props.form.setFieldsValue({
        formOids: undefined,
        businessCode: undefined
      });
      search.search();
    };

    getSearchForm = (key, nowType) => {
      let copySearchForm = deepFullCopy(this.searchForm);
      let options = [
        { label: messages('finance-4.key234')/*报销单*/, value: 'EXP_REPORT' }
      ];
      key !== 'pay_cancel' && (options.push({
        label: messages('finance-4.key233')/*借款单*/,
        value: 'BORROW'
      }));
      copySearchForm.splice(0, 0, {
        id: 'documentCategory', label: messages('finance-4.key60')/*单据类型*/, component: isTitle => <Radio.Group
          onChange={e => this.onRadioChange(isTitle, e.target.value)}
        >
          {
            options.map(item => <Radio key={item.value} value={item.value}>{item.label}</Radio>)
          }
        </Radio.Group>,
        initialValue: 'EXP_REPORT',
        nullValue: 'EXP_REPORT',
        judgeInTitle: true,
        tagParser: value => options.find(item => item.value === value).label
      });
      copySearchForm.map(item => {
        item.id === 'businessCode' && (item.props.params = { status: key });
        if (nowType === 'BORROW') {
          item.id === 'formOids' && (item.props.listExtraParams = { formType: 3001 });
          item.id === 'businessCode' && (item.props.selectorItem = Object.assign(selectorData['business_code_borrow'], { dynamicUrl: true }));
        }
      });
      copySearchForm.deleteObj({ id: 'approveDateRange' }, 'id');
      return copySearchForm;
    };

    handleTableChange = (pagination, filters, sorter) => {
      this.wrappedInstance.setState({
        sortDTOs: sorter.order ? [{
          property: sorter.columnKey,
          direction: sorter.order === 'ascend' ? 'ASC' : 'DESC'
        }] : []
      }, this.wrappedInstance.advancedTableRef.getList);
    };

    renderAllExpandedRow = record => {
      let result = [];
      if (record.warningList) {
        let warningList = JSON.parse(record.warningList);
        let content = '';
        warningList.map(item => {
          if (item.showFlag) {
            content += item.title + '/'
          }
        });
        content && result.push(this.renderExpandedRow(messages('common.label')/*标签*/, content.substr(0, content.length - 1)));
      }
      if (record.printFree) {
        result.push(this.renderExpandedRow(messages('common.print.free')/*免打印*/, messages('common.print.require')/*该报销单无需打印*/));
      }
      if (result.length > 0) {
        return result;
      } else {
        return null;
      }
    };

    renderExpandedRow = (title, content) => {
      return (
        <div>
          <span>{title}</span>:
          <span>{content}</span>
        </div>
      )
    };

    handleRowClick = (record, status) => {
      if (status === 'EXP_REPORT') {
        openSlideFrame.openExpenseReport({
          expenseReportOID: record.entityOid || record.expenseReportOID,
          entry: 'view'
        }, {}, this);
      } else {
        openSlideFrame.openLoanReport({
          formOID: record.formOid,
          loanBillOID: record.entityOid,
          pathname: 'pay-workbench'
        }, {}, this);
      }
    };

    getTotalAmount = data => {
      let res = {};
      data.map(item => {
        res[item.currencyCode] ? res[item.currencyCode] += item.realPaymentAmount : res[item.currencyCode] = item.realPaymentAmount;
      });
      return Object.keys(res).map(item => <span style={{ color: 'rgb(16, 142, 233)' }}>
        {item}{this.filterMoney(res[item], queryCurrencyPrecision(item), true)}&nbsp;&nbsp;
      </span>)
    };

    handleConfirm = (key, searchParams, selectedData, modelEnum) => {
      this.wrappedInstance.setState({ confirmLoading: true });
      confirmPaymentService.confirmPayment(key, this.getSubmitData(searchParams, selectedData, modelEnum)).then(res => {
        this.wrappedInstance.setState({ confirmLoading: false });
        this.confirmSuccess(res.data);
      }).catch(e => {
        this.wrappedInstance.setState({ confirmLoading: false });
        if (e.response.data.errorCode) {
          notification.open({
            message: messages('finance-4.key312')/*确认付款失败*/,
            description: e.response.data.message,
            icon: <Icon type="frown-circle" style={{ color: '#e93652' }}/>
          });
        } else {
          if (e.name === 'SyntaxError')
            this.confirmSuccess();
          else
            notification.open({
              message: messages('finance-4.key312')/*确认付款失败*/,
              description: messages('common.error')/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/,
              icon: <Icon type="frown-circle" style={{ color: '#e93652' }}/>
            });
        }
      })
    };

    getSubmitData = (searchParams, selectedData, modelEnum) => {
      selectedData = selectedData.map(item => item.id);
      searchParams.entityType = searchParams.documentCategory === 'EXP_REPORT' ? 1002 : 3001;
      let temp = { ...searchParams, modelEnum };
      temp[modelEnum === 'CURRENT_PAGE' ? 'currentPageIds' : 'excludeIds'] = selectedData;
      return temp;
    };

    confirmSuccess = (data = {}) => {
      if (data.failNum) {
        notification.open({
          message: messages('finance-4.key312')/*确认付款失败*/,
          description: messages('finance-4.key329',{arg1: data.successNum,arg2: data.failNum})/*付款成功{arg1}条，失败{arg2}条*/,
          icon: <Icon type="frown-circle" style={{ color: '#e93652' }}/>,
        });
      } else {
        notification.open({
          message: messages('finance-4.key330')/*发起支付成功*/,
          description: messages('finance-4.key331')/*请稍后确认支付结果*/,
          icon: <Icon type="smile-circle" className='default-color-font'/>,
        });
      }
      this.clearRowSelection();
      this.wrappedInstance.advancedTableRef.getList();
    };

    clearRowSelection = () => {
      let { rowSelection } = this.wrappedInstance.state;
      rowSelection.selectedRowKeys = [];
      this.wrappedInstance.setState({
        rowSelection: rowSelection,
        selectedData: [],
        modelEnum: 'CURRENT_PAGE'
      });
    };

    handleCancelPay = (key, searchParams, selectedData, modelEnum) => {
      this.wrappedInstance.setState({ cancelLoading: true });
      let params = this.getSubmitData(searchParams, selectedData, modelEnum);
      confirmPaymentService.cancelPayment(key, params, true).then(() => {
        this.wrappedInstance.setState({ cancelPayModal: true, cancelLoading: false, params });
      }).catch((e) => {
        message.error(e.response.data.message);
        this.wrappedInstance.setState({ cancelLoading: false })
      });
    };

    renderDropDown = () => {
      return (
        <Menu onClick={this.dropDownChange}>
          <Menu.Item key="CURRENT_PAGE">{messages('finance-4.key332')/*全选当页*/}</Menu.Item>
          <Menu.Item key="ALL_PAGE">{messages('finance-4.key333')/*全选全部*/}</Menu.Item>
        </Menu>
      )
    };

    dropDownChange = item => {
      let { rowSelection, modelEnum } = this.wrappedInstance.state;
      const { dataSource } = this.wrappedInstance.advancedTableRef.state;
      if (modelEnum === item.key) {
        return;
      }
      rowSelection.selectedRowKeys = [];
      if (item.key !== 'CURRENT_PAGE') {
        rowSelection.selectedRowKeys = dataSource.map(item => item.id);
      }
      this.wrappedInstance.setState({
        modelEnum: item.key,
        rowSelection: rowSelection,
        selectedData: []
      });
    };

    onSelectChange = selectedRowKeys => {
      let { rowSelection } = this.wrappedInstance.state;
      rowSelection.selectedRowKeys = selectedRowKeys;
      this.wrappedInstance.setState({ rowSelection });
    };

    onSelectItem = (record, selected) => {
      const { selectedData } = this.wrappedInstance.state;
      if (selected === this.judgePage()) {
        selectedData.push(record)
      } else {
        selectedData.deleteObj(record, 'id')
      }
      this.wrappedInstance.setState({ selectedData });
    };

    onSelectAll = (selected, selectedRows, changeRows) => {
      changeRows.map(changeRow => this.onSelectItem(changeRow, selected));
    };

    judgePage = () => {
      return this.wrappedInstance ? this.wrappedInstance.state.modelEnum === 'CURRENT_PAGE' : true
    };

    getSelection = () => {
      return {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      }
    };

    onGetData = (dataSource, pagination, searchParams, sourceSearchParams) => {
      this.props.translateParams(sourceSearchParams);
      if (this.judgePage()) {
        return -1;
      }
      const { selectedData, rowSelection } = this.wrappedInstance.state;
      if (rowSelection) {
        dataSource.forEach(item => rowSelection.selectedRowKeys.addIfNotExist(item.id));
        selectedData.forEach(item => rowSelection.selectedRowKeys.delete(item.id));
      }
      this.wrappedInstance.setState({ rowSelection });
    };

    render() {
      let props = { ...this.props, ref: this.setWrappedInstance };
      return (
        <WrappedComponent
          {...props}
          getColumns={this.getColumns}
          getSearchForm={this.getSearchForm}
          getTotalAmount={this.getTotalAmount}
          handleChangeStatus={this.handleChangeStatus}
          handleCancelPay={this.handleCancelPay}
          handleConfirm={this.handleConfirm}
          clearRowSelection={this.clearRowSelection}
          renderDropDown={this.renderDropDown}
          handleTableChange={this.handleTableChange}
          getSelection={this.getSelection}
          onGetData={this.onGetData}
          handleRowClick={this.handleRowClick}
          getSubmitData={this.getSubmitData}
          confirmSuccess={this.confirmSuccess}
          judgePage={this.judgePage}
        />
      )
    }

  }

  return Hoc;

};

export default DataHoc
